import { request } from "/utils/request/index.js";
import JSEncrypt from "/node_modules/.vite/deps/jsencrypt.js?v=afd20174";

let userId = null;
function encryptObj(obj) {
  let PUBLIC_KEY =
    "MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQAodPxHJexHav2lQeI8Z6YOG6wnudaurMB/CBFdxgZkAGp9p+7WfScfBStsYoSMiwZo6i1Iv+4YS6Rfy6fNvoeN1YP4mKDKi9LNydzLK4Iz7Zn7/KLUbYfdf3GAxw0vkiJ+TnEp74TssinaWaPDVT5ZN2lak5Gq+TVw/7j1M4bcWKNxWKIyha9CxPEjym3N4FqbRT4K2FauYc7r910alpGa+MpRFPURg6H9uD1mJltzl7RWH9lfA7nWmQebZQAjxpYlPJwehbEY/F0uTa+NnTAn8nwXgcojDR1BkGgUBSMFUtJlxn7GHoNs7H0PBlBCje636ZBPTwHJVTSf42bzz8bfAgMBAAE=";
  // 旧网关 公钥 PUBLIC_KEY = 'MIIBITANBgkqhkiG9w0BAQEFAAOCAQ4AMIIBCQKCAQAodPxHJexHav2lQeI8Z6YOG6wnudaurMB/CBFdxgZkAGp9p+7WfScfBStsYoSMiwZo6i1Iv+4YS6Rfy6fNvoeN1YP4mKDKi9LNydzLK4Iz7Zn7/KLUbYfdf3GAxw0vkiJ+TnEp74TssinaWaPDVT5ZN2lak5Gq+TVw/7j1M4bcWKNxWKIyha9CxPEjym3N4FqbRT4K2FauYc7r910alpGa+MpRFPURg6H9uD1mJltzl7RWH9lfA7nWmQebZQAjxpYlPJwehbEY/F0uTa+NnTAn8nwXgcojDR1BkGgUBSMFUtJlxn7GHoNs7H0PBlBCje636ZBPTwHJVTSf42bzz8bfAgMBAAE='
  let encrypt = new JSEncrypt();
  encrypt.setPublicKey(PUBLIC_KEY);
  let entcrytString = JSON.stringify(obj);
  return encrypt.encrypt(entcrytString);
}

export async function authPost(path, params = {}) {
  let isDev = "development" === "development";
  console.log("request payload", params);
  // userId="1120101001"; //  画报聚合页测试id
  // userId="1010100189"; //  咨询记录页测试id
  userId = params.userId;
  if (!userId || userId.length <= 0) {
    return {
      msg: "登录超时，请重新登录！",
      code: -1,
      ok: false,
    };
  }
  params["userId"] = userId;
  let payload = {};
  // params['reqParam'] = encryptObj({ userId })
  // payload = params
  payload = {
    encryptParam: encryptObj(params),
  };
  if (isDev) {
    payload.defaultParams = params;
  }
  const res = await request(path, payload);
  return res;
}

export async function nativeRequest(params) {
  // userid走原生，此处无需传递
  let waitCount = 0;
  const method = params.method;
  console.log("param", params);
  return new Promise((resolve, reject) => {
    const onSuccess = (res) => {
      try {
        let data = {};
        if (res) {
          //请求失败返回空字符串
          let resData = JSON.parse(res).data;
          if (typeof resData === "string") {
            data = JSON.parse(resData);
          } else {
            data = resData;
          }
          console.log("res data str", typeof resData, data);
        } else {
          console.log("err!! res:", res);
        }
        resolve({
          ok: !!res, // 成功的错误码
          code: 0,
          msg: res || "no data",
          data,
        });
      } catch (e) {
        resolve({ msg: "数据异常", ok: 0 });
        console.log("res parse err", e);
      }
    };
    const onError = (e) => {
      console.log("ai_webview_net err", e);
      resolve({ msg: "请求异常", ok: 0 });
    };
    setTimeout(() => {
      resolve({ msg: "请求超时", ok: 0, code: -1 });
    }, 15000);
    (function waitCordova() {
      if (window.cordova && typeof window.cordova.exec === "function") {
        console.log(
          "cordovaReq is ready,",
          window.cordova,
          window.cordova.exec
        );
        window.cordova.exec(onSuccess, onError, "aiPlugin", "ai_webview_net", {
          method,
          params,
        });
      } else {
        console.log("cordovaReq not ready", waitCount, window.cordova);
        setTimeout(waitCordova, 30);
      }
    })();
  });
}


export async function tttPost(path, params = {}) {
  let isDev = "development" === "development";
  console.log("request payload", params);
  userId = params.userId;
  if (!userId || userId.length <= 0) {
    return {
      msg: "登录超时，请重新登录！",
      code: -1,
      ok: false,
    };
  }
  params["userId"] = userId;
  let payload = {};
  // params['reqParam'] = encryptObj({ userId })
  // payload = params
  payload = {
    appId:'LBDP-TTT',
    encryptParam: encryptObj(params),
    //headerContentType:'application/x-www-form-urlencoded; charset=utf-8',
  };
  if (isDev) {
    payload.reqParam = JSON.stringify(params);
  }
  const res = await request(path, payload);
  return res;
}
